import Vue from 'vue'
import Router from 'vue-router'
import { getToken } from '@/utils/auth' // getToken from cookie

Vue.use(Router)

const whiteList = ['/login', '/register','/404']// no redirect whitelist

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      name: 'Login',
      component:  () => import('./views/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('./views/Register.vue')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('./views/Home.vue')
    },
    {
      path: '/404',
      component: () => import('@/views/errorPage/404')
    },
    { 
      path: '*', 
      redirect: '/404'
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (getToken()) { // determine if there has token
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/home' })
    } else{
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

export default router